package utils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ControleFile {

	public String champs;
	public String value;
	public long maxsize;
	public boolean isRequired;
	public String errorFind;
	public char type;
	
	public ControleFile(String champs, String value, long maxsize, boolean isRequired,char type) {
		super();
		this.champs = champs;
		this.value = value;
		this.maxsize = maxsize;
		this.isRequired = isRequired;
		this.type = type;
	}

	public boolean controlValue(){
		if(!verifyIsRequired()){ errorFind = "Le champ "+champs+" doit être renseigné"; return false; }
		if(!verifyIsGoodType()) return false;
		if(!verifyIsTooLong()) { errorFind = "Erreur sur la longueur du champ"; return false; }
		return true;
	}
	
	private boolean verifyIsTooLong(){
		return maxsize > 0 ? value.length() <= maxsize : true;
	}
	
	private boolean verifyIsRequired(){
		return (isRequired && value != null);
	}
	
	private boolean verifyIsGoodType(){
		switch(type){
		case 'N':
			if(!verifyFormatNumber()) errorFind = "Format invalide";
			break;
		case 'D':
			if(verifyFormatDate()){
				if(!verifyDate()) errorFind = "Date invalide";
			}else errorFind = "Format de date invalide";				
			break;
		case 'C':
			break;
		}
		return errorFind == null;
	}
	
	private boolean verifyDate(){
		boolean isExistingDate = true;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        Date stringToDate = new Date();
        try {
        	stringToDate = sdf.parse(value);
            String formatDate = sdf.format(stringToDate);
            if(formatDate.compareTo(value) !=  0) isExistingDate = false;
        } catch (Exception e) {
                System.out.println("Exception");
        }
		return isExistingDate;
	}
	
	private boolean verifyFormatDate(){
		return value.matches("^([0-9]{2})(\\/)([0-9]{2})(\\/)(\\d\\d\\d\\d)$");
	}
	
	private boolean verifyFormatNumber(){
		return value.matches("^(\\d*).\\d{1,2}$");
	}	
}
